const hljs = require('highlight.js')
const mdContainer = require('markdown-it-container')
// const mermaid = require('mermaid')

const md = require('markdown-it')({
  linkify: true,
  typographer: true,
  html: true,
  highlight: function (str, lang) {
    if (lang === 'linear') {
      return '<pre-linear list="' + str + '"></pre-linear>'
    }
    if (!lang || !hljs.getLanguage(lang)) {
      return '<pre><code class="hljs">' + str + '</code></pre>'
    }
    const html = hljs.highlight(lang, str, true, undefined).value
    return `<pre><code class="hljs language-${lang}">${html}</code></pre>`
  }
})

md.use(mdContainer, 'demo', {

  validate: function(params) {
    return params.trim().match(/^demo\s*(.*)$/)
  },

  render: function (tokens, idx) {
    var m = tokens[idx].info.trim().match(/^demo\s*(.*)$/)
    if (tokens[idx].nesting === 1) {
      const description = m && m.length > 1 ? m[1] : ''
      const content = tokens[idx + 1].type === 'fence' ? tokens[idx + 1].content : ''
      return `<el-card>
      ${description ? `<div>${md.render(description)}</div>` : ''}
      <!--element-demo: ${content}:element-demo-->
      `
    }
    return '</el-card>'
  }
})

md.use(mdContainer, 'tip')
md.use(mdContainer, 'warning')

module.exports = (file) => {
  let newFile = md.render(file)
  let prefix = '<!--element-demo:'
  let suffix = ':element-demo-->'
  newFile = newFile.replace(new RegExp(prefix, 'gi'), '<el-row>')
  newFile = newFile.replace(new RegExp(suffix, 'gi'), '</el-row>')
  newFile = newFile.replace(/<\/?template>/g, '')
  let content = `
    <template>
      <section class="markdown">
        ${newFile}
      </section>
    </template>
  `
  return content;
};


// var graph = mermaid.mermaidAPI.render('graphDiv', graphDefinition, insertSvg);